import type {
  Request,
  ResponseToolkit,
  ServerRoute,
  ReqRefDefaults,
} from "@hapi/hapi";
import path from "path";
import puppeteer from "puppeteer";
import os from "os";
import { User, Notes } from "../model/index";
declare global {
  interface Window {
    setData: (data: any) => void;
  }
}
const getFilename = (filename: string) => {
  return Date.now() + Math.floor(Math.random() * 10000) + filename;
};
const initPdf = async (notes: any) => {
  console.log(notes, "d");
  try {
    const NODE_ENV = process.env.NODE_ENV;
    let args: string[] = [];
    if (os.type() == "Linux") {
      args = ["--no-sandbox", "--disable-setuid-sandbox"];
    }
    const browser = await puppeteer.launch({
      headless: true,
      args,
    });

    const page = await browser.newPage();

    await page.addStyleTag({ content: 'body { font-family: "SimSun"; }' });

    // 设置页面大小
    await page.setViewport({ width: 794, height: 1123 });
    // 加载页面
    await page.goto(
      NODE_ENV == "dev"
        ? "http://127.0.0.1:5173/"
        : "http://47.100.120.66:8888/",
      {
        waitUntil: "networkidle0",
      }
    );

    // 设置页面背景色
    await page.evaluate((data) => {
      (window as any).setData(data);
    }, notes);

    // await page.waitForSelector(".img");

    await page.waitForFunction(() => {
      const images = document.querySelectorAll("img");
      return (
        Array.from(images).every(
          (img) => img.complete && img.naturalWidth !== 0
        ) && document.querySelectorAll("*").length > 0
      );
    });
    // 将页面转换为PDF
    const baseUrl = "/api/pdf/";
    const pdfUrl = getFilename("notes.pdf");
    await page.pdf({
      printBackground: true,
      path: path.resolve(__dirname, "../../public/pdf", pdfUrl),
      format: "A4",
    });
    await browser.close();

    return `${baseUrl}${pdfUrl}`;
  } catch (error) {
    console.log(error);
    return error;
  }
};
let route: ServerRoute<ReqRefDefaults> = {
  path: "/getPdf",
  method: "post",
  handler: async (r: any, h: ResponseToolkit) => {
    console.log(r.payload);
    try {
      const data = {
        ...r.payload,
      };
      await Notes.updateOne({ _id: data._id }, { ...data });
      let pdfUrl = await initPdf(data);
      return pdfUrl;
    } catch (err: any) {
      if (err.code === 11000) {
        console.log(err);
        // 如果出现重复键值错误，则返回适当的错误消息
        return h.response().code(400);
      } else {
        // 否则返回通用错误消息
        console.log("error here");
        return h
          .response({
            error: { message: "服务器内部错误", code: err.code || 500 },
          })
          .code(500);
      }
    }
  },
  options: {
    plugins: {
      "hapi-swagger": {
        security: [{ apiKey: [] }],
      },
    },
    payload: {
      parse: true, // 解析请求体
      allow: "application/json", // 允许JSON格式的请求体
    },
    // auth: false,
    tags: ["api"],
  },
};
export default route;
